-- 后端节点的主文件， 会被命名成 .router
-- 这个是运行在node节点上的一个router，处理所有来访问这个节点的请求
-- 后台节点，只有不同节点， 本节点之间的调用
-- 不同节点调用，全部走 .router 来调用， 本节点调用，全部使用一级命令的模式，而且不用process了
local filename = "router.lua"

local skynet = require "skynet"
local cluster = require "skynet.cluster"
require "skynet.manager"

local filelog = require "filelog"
local routerbase = require "routerbase"
local httpc = require "http.httpc"
local timetool = require "timetool"
local json = require "cjson"
json.encode_sparse_array(true, 1, 1)

local Router = routerbase:new()

local is_set_dns = false

--历史记录url
local history_url = "http://wtapi01.streamingvds.com:3800/v1/client2OpenCard/history"

--桌子信息url
local tableinfo_url = "http://wtapi01.streamingvds.com:3800/v1/client2OpenCard/getCmd"

-------------------------------

local function http_post(host, url, req_body, recvheader)
	local header = {
		["content-type"] = "application/json"
	}

	return httpc.request("POST", host, url, recvheader, header, json.encode(req_body))
end

-------------------------------

function  Router:init()
	--todo
end

--
--发送http请求
--
function Router:send_http_request(request_url, request_body)
	local host,url = string.match(request_url,"://(.+%.[%w:]+)/(.+)")
	local recvheader = { }
	url = "/" .. (url or "") 
	
	filelog.sys_info("---start http request---", host, url)
	if not is_set_dns then
		skynet.pcall(httpc.dns) -- 异步dns服务，只设置一次
		is_set_dns = true
	end
	httpc.timeout = 300	        -- 超时3s
	local isok,status,body = skynet.pcall(http_post, host, url, request_body or {}, recvheader)
	filelog.sys_info("---end http request---", status, body, host, url)
	if status == 200 and body then
		return body
	elseif not isok then
		skynet.pcall(httpc.dns)
		return false
	end

	return 
end

---------------------------------

-- 获取牌桌历史记录
function Router.CMD.get_table_history(tableKey)
	local now = timetool.get_time()
	local hour = tonumber(os.date("%H", now))
	local cur_hour = string.format("%02d", hour)
	local lst_hour = string.format("%02d", (hour + 23) % 24)
	local fmt_date = os.date("%Y%m%d ", now)
	local request_body = {
		tableKey = tableKey,
		date = fmt_date .. cur_hour,
		row = 100,
		gameRound = "",
	}
	
	--获取当前局数
	local result = nil
	local tableinfo = Router.CMD.get_table_info(tableKey)
	if tableinfo then
		local curround = 0
		local gameround = 0
		local gamedata = json.decode(tableinfo)
		if gamedata.tlsNewGame and gamedata.tlsNewGame.tableKey == tableKey then
			curround = tonumber(gamedata.tlsNewGame.round)
			gameround = string.sub(gamedata.tlsNewGame.gameRound, -3, -1)
			if curround > 100 then curround = 100 end
			request_body.row = curround
			request_body.date = fmt_date .. cur_hour
			result = Router:send_http_request(history_url, request_body)
			if not result then
				filelog.sys_error("get table history failed!", result)
				return false
			end
			
			--获取额外记录
			local exthistorys = nil
			local historys = json.decode(result) or {}
			if historys.run_report and tonumber(historys.run_report.code) == 1 then
				local cur_rows = tonumber(historys.run_report.total_rows)
				if cur_rows < curround then
					request_body.row = curround - cur_rows
					request_body.date = fmt_date .. lst_hour
					result = Router:send_http_request(history_url, request_body)
					if not result then
						filelog.sys_error("get table history failed!", result)
						return false
					end
					exthistorys = json.decode(result)
					if not exthistorys.run_report or tonumber(exthistorys.run_report.code) ~= 1 then
						exthistorys = nil
					end
				end 
			else
				filelog.sys_error("get table history failed!", historys)
				return false
			end
			
			--保存记录
			local allrecords = historys.detail or {}
			if exthistorys and exthistorys.detail then
				for i,item in ipairs(exthistorys.detail) do
					table.insert(allrecords, item)
				end
			end
			
			return allrecords
		end
	end
	
	--未拉取到记录，返回最近100局
	result = Router:send_http_request(history_url, request_body)
	if not result then
		filelog.sys_error("get table history failed!", result)
		return false
	end
	local historys = json.decode(result)
	if historys and historys.run_report and tonumber(historys.run_report.code) == 1 then
		return historys.detail
	end
	
	return {}
end

--获得桌子信息
function Router.CMD.get_table_info(tableKey)
	local request_body = {
		tableKey = tableKey,
	}
	
	local result = Router:send_http_request(tableinfo_url, request_body)
	if not result then
		filelog.sys_error("get table info failed!", result)
	end
	
	return result
end

skynet.start(function()
	Router:start()
end)
